<?php
/**
 * Created by PhpStorm.
 * User: henry
 * Date: 2017/6/6
 * Time: 下午12:35
 */

namespace common\mongo;


use MongoDB\Driver\Exception\Exception;

class Collection extends \yii\mongodb\Collection
{
    /**
     * Update the existing database data, otherwise insert this data
     * @param array|object $data data to be updated/inserted.
     * @param array $options list of options in format: optionName => optionValue.
     * @return string updated/new record id instance.
     * @throws Exception on failure.
     */
    public function save($data, $options = [])
    {
        if (empty($data['_id'])) {
            return strval($this->insert($data, $options));
        } else {
            $id = $data['_id'];
            unset($data['_id']);
            $this->update(['_id' => $id], ['$set' => $data], ['upsert' => true]);
            return is_object($id) ? strval($id) : $id;
        }
    }
}